package com.myfum.mobile.tetris.views
{
	import com.myfum.mobile.tetris.Config;
	import com.myfum.mobile.tetris.data.cubes.CubeType;
	import com.myfum.mobile.tetris.events.P2PEvent;
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.utils.ByteArray;
	
	import org.robotlegs.mvcs.Mediator;
	
	public class ScreenDrawerMediator extends Mediator
	{
		[Inject]
		public var view:ScreenDrawer;
		
		public function ScreenDrawerMediator()
		{
			super();
		}
		
		override public function onRegister():void{
			eventMap.mapListener(eventDispatcher, P2PEvent.MESSAGE_RECIEVED, onMessage);
		}
		
		private function onMessage(e:P2PEvent):void{
			redraw(e.info);
		}
		
		private function redraw(info:Object):void{
			if(info == null){
				return;
			}
			var byte:ByteArray = info.message;
			byte.uncompress();
			var obj:Object = byte.readObject();
			var map:String = obj.map;
			var shape:String = obj.shape;
			
			var bd:BitmapData = view.getBitmap().bitmapData;
			bd.lock();
			for(var i:int = 0;i<map.length;i++){
				var p:Point = new Point(i%10, Math.floor(i/10));
				fillCube(bd, p, int(map.charAt(i)));
			}
			if(shape){
				var cubeArr:Array = shape.split(",");
				for(i = 0;i<cubeArr.length;i++){
					var s:String = cubeArr[i] as String;
					var p1:Point = new Point();
					p1.x = s.split('-')[0];
					p1.y = s.split('-')[1];
					
					fillCube(bd, p1, CubeType.DROPING);
				}
			}
			bd.unlock();
		}
		
		private function fillCube(bd:BitmapData, p:Point, type:int):void{
			var source:BitmapData;
			switch(type){
				case CubeType.EMPTY:
					source = Config.empty_cube_small;
					break;
				case CubeType.STANDING:
				case CubeType.DROPING:
					source = Config.default_cube_small;
					break;
				case CubeType.BOMB:
					source = Config.bomb_cube;
					break;
				case CubeType.UNBREAKABLE:
					source = Config.stone_cube;
					break;
			}
			bd.copyPixels(source, source.rect, new Point(Config.CUBE_SMALL_SCREEN*p.x, Config.CUBE_SMALL_SCREEN*(p.y)));
		}
	}
}